#include "sim_status_provider.h"
#include "application/simulation/simulation_engine.h"
#include <QDateTime>

namespace application {
namespace simulation {

SimStatusProvider::SimStatusProvider(
    int agvNumber,
    SimulationEngine* engine,
    std::shared_ptr<kernel::ILogger> logger,
    QObject* parent)
    : QObject(parent)
    , m_agvNumber(agvNumber)
    , m_engine(engine)
    , m_logger(logger)
    , m_timer(new QTimer(this))
    , m_running(false)
    , m_updateIntervalMs(DEFAULT_UPDATE_INTERVAL_MS)
{
    connect(m_timer, &QTimer::timeout, this, &SimStatusProvider::onTimerTimeout);
}

kernel::Result<void> SimStatusProvider::start() {
    if (m_running) {
        return kernel::Result<void>::success();
    }

    m_running = true;
    m_timer->setInterval(m_updateIntervalMs);
    m_timer->start();

    if (m_logger) {
        const QString msg = QStringLiteral("SimStatusProvider AGV%1: 开始状态推送，间隔 %2ms")
                                .arg(m_agvNumber)
                                .arg(m_updateIntervalMs);
        m_logger->info(msg);
    }

    return kernel::Result<void>::success();
}

void SimStatusProvider::stop() {
    if (!m_running) {
        return;
    }

    m_running = false;
    m_timer->stop();

    if (m_logger) {
        m_logger->info(
            QStringLiteral("SimStatusProvider AGV%1: 停止状态推送")
                .arg(m_agvNumber));
    }
}

bool SimStatusProvider::isRunning() const {
    return m_running;
}

void SimStatusProvider::setStatusUpdateCallback(StatusUpdateCallback callback) {
    m_callback = callback;

    if (m_logger) {
        m_logger->debug(
            QStringLiteral("SimStatusProvider AGV%1: 设置状态回调")
                .arg(m_agvNumber));
    }
}

void SimStatusProvider::setUpdateInterval(int intervalMs) {
    m_updateIntervalMs = intervalMs;
    if (m_running) {
        m_timer->setInterval(intervalMs);
    }
}

void SimStatusProvider::updateStatus() {
    if (!m_callback || !m_engine || !m_engine->physicsSimulator()) {
        return;
    }

    // 从物理模拟器获取车辆状态
    auto state = m_engine->physicsSimulator()->getState(m_agvNumber);

    // 构造 AgvStatusDTO
    kernel::dtos::AgvStatusDTO dto;
    dto.agvNumber = m_agvNumber;

    // 位置信息 (统一使用米)
    dto.x = state.position.x();
    dto.y = state.position.y();
    dto.angle = state.heading;

    // 运动信息 (统一使用米/秒)
    dto.vx = state.velocity;
    dto.vy = 0.0;
    dto.w = 0.0;

    // 站点信息
    dto.lastStation = state.lastStation;

    if (!state.pathStations.empty() && state.currentSegmentIndex < state.pathStations.size()) {
        dto.currentStation = QString::fromStdString(state.pathStations[state.currentSegmentIndex]);
        dto.targetId = QString::fromStdString(state.pathStations.back());

        // 构建未完成路径
        for (size_t i = state.currentSegmentIndex; i < state.pathStations.size(); ++i) {
            dto.unfinishedPath.append(QString::fromStdString(state.pathStations[i]));
        }
    } else {
        dto.currentStation = state.lastStation;
        dto.targetId = "";
    }

    // 地图信息
    dto.current_map = state.currentMap;

    // 导航状态 (使用 DTO 中的 taskStatus 字段，类型为 int)
    if (state.pathStations.empty()) {
        dto.taskStatus = 0;  // TaskStatus::None
        dto.taskType = 0;    // TaskType::None
    } else if (state.isPaused) {
        dto.taskStatus = 3;  // TaskStatus::Suspended
        dto.taskType = 3;    // TaskType::PathNavToStation
    } else {
        dto.taskStatus = 2;  // TaskStatus::Running
        dto.taskType = 3;    // TaskType::PathNavToStation
    }

    // 其他默认状态
    dto.batteryLevel = state.batteryLevelPercent;  // 上层转换为整数百分比
    dto.charging = state.charging;
    dto.blocked = false;
    dto.confidence = 1.0;
    dto.mode = 1;  // 自动模式

    // 停止状态
    dto.isStop = (state.velocity < 0.01);

    // 调用回调推送状态
    m_callback(dto);
}

void SimStatusProvider::onTimerTimeout() {
    if (m_running) {
        updateStatus();
    }
}

} // namespace simulation
} // namespace application
